package printlevels

import scala.collection.mutable.Queue

/**
 * Prints a binary tree by level using a <tt>Queue</tt>.
 * For example, given the tree below:
 * 
 * <pre>
 *       1
 *     /   \
 *    2     3
 *   / \   / \
 *  4   5 6   7
 * </pre>
 * 
 * The output should be:
 * 
 * <pre>
 * 1
 * 2 3
 * 4 5 6 7
 * </pre>
 */
object Main {

  type N = Int

  class Node(val value: N,
             val left: Node = null,
             val right: Node = null)

  def printLevels(node: Node): Unit = {
    printLevels(Queue[Node]() += node)
  }

  def printLevels(nodes: Queue[Node]): Unit = {
    val children = Queue[Node]()
    nodes.foreach { node => 
      print(node.value)
      print(' ')
      if (node.left != null)
        children += node.left
      if (node.right != null)
        children += node.right
    }
    println
    if (children.nonEmpty)
      printLevels(children)
  }

  def main(args: Array[String]): Unit = {
    printLevels(
      new Node(
        1,
        new Node(2, new Node(4), new Node(5)),
        new Node(3, new Node(6), new Node(7))))
  }
}
